import React from 'react';
import { Form, Input, Button, message, Modal, Select, DatePicker, InputNumber, Space, Tabs, Radio, Upload } from 'antd';
import {
    ExclamationCircleOutlined, LoadingOutlined, PlusOutlined
} from '@ant-design/icons';
import { connect } from 'umi';
import 'braft-editor/dist/index.css'
import UploadUtil from '../../../components/UploadUtil';
import moment from 'moment';
import G2Line from '../../Charts/G2Line';

const { confirm } = Modal;
const { TabPane } = Tabs;

class ChildEdit extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            datas: {},
            farthers: [],
            mothers: [],
            inputValue: [7, 30],
            imageUrl: '',
            imgList: [],
            GrowthData: [],
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        const { ParentData } = this.props;
        this.fetchParents();
        if (ParentData && ParentData.id) {
            this.getData(ParentData.id);
            this.setState({ datas: ParentData });
            this.fetchGrowthData(ParentData.id)
        }
    }
    getData = (id: number) => {
        const { dispatch } = this.props;
        if (id) {
            dispatch({
                type: 'Abp/get',
                payload: { id },
                control: 'Edu_Children',
            }).then(() => {
                var result = this.props.response.result;
                if (result.avatar) {
                    this.setState({ imageUrl: result.avatar });
                }
                result.birthday = moment(result.birthday);
                this.setState({ datas: result });
                this.formRef.current.setFieldsValue({ model: result });
            });
        }
    }
    fetchGrowthData = (id: number) => {
        this.props.dispatch({
            type: "Abp/getList",
            payload: { SkipCount: 0, MaxResultCount: 100, childId: id, eType: 'basic' },
            control: 'Edu_EventGrowth'
        }).then(() => {
            var resp = this.props.response;
            if (resp) {
                var dataSource = resp.result.items;
                var gdata: any = [];
                dataSource.forEach((element: any) => {
                    let obj = {
                        day: moment(element.eventDate).format("MM-DD"),
                        ctype: '身高',
                        value: element.height,
                    }
                    gdata.push(obj);
                    obj = {
                        day: moment(element.eventDate).format("MM-DD"),
                        ctype: '体重',
                        value: element.weight,
                    }
                    gdata.push(obj);
                    obj = {
                        day: moment(element.eventDate).format("MM-DD"),
                        ctype: '头围',
                        value: element.headCirc,
                    }
                    gdata.push(obj);
                });
                this.setState({ GrowthData: gdata });
            }
        });
    }
    fetchParents = () => {
        this.props.dispatch({
            type: "Abp/getAll",
            payload: { SkipCount: 0, MaxResultCount: 10000 },
            control: 'Members'
        }).then(() => {
            var result = this.props.response.result.items;
            if (result) {
                var fathers = result.filter((o: any) => o.role == "父亲" || o.role == "爸爸");
                var mothers = result.filter((o: any) => o.role == "母亲" || o.role == "妈妈");
                this.setState({ mothers, fathers });
            }
        })
    }
    onFinish = async (values: any) => {
        var act = "Abp/create";
        if (values.model.id) {
            act = "Abp/update";
        }
        values.model.contents = this.state.contentEditor;
        if (this.state.imageUrl) {
            values.model.avatar = this.state.imageUrl;
        }
        this.props.dispatch({
            type: act,
            payload: values.model,
            control: 'Edu_Children',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('保存成功！');
                this.props.fetchDatas();
            }
            else {
                message.error('保存错误，请联系管理员');
            }
        });
    };
    ResetForm = () => {
        var data = {
            id: 0,
        }
        this.setState({ datas: data });
        this.formRef.current.resetFields();
    }
    handleDel = () => {
        this.props.dispatch({
            type: "Abp/delete",
            payload: { Id: this.state.datas.id },
            control: 'Edu_Children',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('删除成功！');
                this.props.fetchDatas();
                this.formRef.current.resetFields();
            }
            else {
                message.error('删除错误，请联系管理员！');
            }
        })
    }
    showConfirm = () => {
        var _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.handleDel();
            },
            onCancel() { },
        });
    }
    handleChange = (editorState: any) => {
        this.setState({
            contentEditor: editorState.toHTML(),
        });
    }
    onChange = (value: number[]) => {
        this.setState({
            inputValue: value,
        });
    };
    handleUpload = (info: any) => {
        if (info.file.status === 'done' && info.file.response) {
            this.setState({
                imageUrl: info.file.response.result
            })
        }
    };
    g2LineBsc: any = React.createRef();
    onRef = (ref: any) => {
        this.g2LineBsc = ref
    }
    render() {
        const { datas, imageUrl, loading } = this.state;
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传照片</div>
            </div>
        );
        return (
            <div>
                <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish} >
                    <Tabs defaultActiveKey="1" >
                        <TabPane tab="基本" key="1">
                            <div style={{ display: 'none' }}>
                                <Form.Item
                                    label="id"
                                    name={['model', 'id']}>
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    name={['model', 'avatar']}>
                                    <Input />
                                </Form.Item>
                            </div>
                            <Form.Item style={{ marginBottom: 0 }}>
                                <Input.Group compact>
                                    <Form.Item
                                        name={['model', 'fatherId']}
                                        label="父亲">
                                        <Select
                                            style={{ width: 175 }}
                                            showSearch
                                            placeholder="请选择父亲"
                                            filterOption={(input, option: any) =>
                                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }>
                                            {
                                                this.state.fathers?.map((item: any) => {
                                                    return (<Select.Option key={item.id} value={item.id}>{item.nickname}</Select.Option>)
                                                })
                                            }

                                        </Select>
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'motherId']}
                                        label="母亲">
                                        <Select
                                            style={{ width: 175 }}
                                            showSearch
                                            placeholder="请选择母亲"
                                            filterOption={(input, option: any) =>
                                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }>
                                            {
                                                this.state.mothers?.map((item: any) => {
                                                    return (<Select.Option key={item.id} value={item.id}>{item.nickname}</Select.Option>)
                                                })
                                            }
                                        </Select>
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>

                            <Form.Item style={{ marginBottom: 0 }}>
                                <Input.Group compact>
                                    <Form.Item
                                        name={['model', 'name']}
                                        label="宝宝名"
                                        rules={[{ required: true, message: "请输入宝宝名" }]}>
                                        <Input />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'nickname']}
                                        label="宝宝昵称">
                                        <Input />
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>
                            <Form.Item>
                                <Upload
                                    action={UploadUtil.actionURL}
                                    headers={{
                                        'Authorization': UploadUtil.accessToken,
                                    }}
                                    data={{
                                        objectId: datas.id,
                                        objectName: 'Edu_Children',
                                        objectField: 'Avatar'
                                    }}
                                    name="files"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    beforeUpload={UploadUtil.beforeUpload}
                                    onChange={this.handleUpload}
                                >
                                    {imageUrl ? <img src={UploadUtil.imgServ + imageUrl} alt="avatar" style={{ width: '100%',height:'100%' }} /> : uploadButton}
                                </Upload>
                            </Form.Item>
                            <Form.Item style={{ marginBottom: 0 }}>
                                <Input.Group compact>
                                    <Form.Item
                                        name={['model', 'idNo']}
                                        label="身份证号">
                                        <Input />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'birthday']}
                                        label="出生年月">
                                        <DatePicker />
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>

                            <Form.Item
                                name={['model', 'memo']}
                                label="宝宝简介"
                                rules={[{ required: true, message: "请输入宝宝简介" }]}>
                                <Input.TextArea />
                            </Form.Item>
                            <Form.Item style={{ marginBottom: 0 }}>
                                <Input.Group compact>
                                    <Form.Item
                                        name={['model', 'age']}
                                        label="年龄"
                                        rules={[{ required: true, message: "请输入宝宝年龄" }]}>
                                        <InputNumber min={1} />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'height']}
                                        label="身高(cm)">
                                        <InputNumber min={0} />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'weight']}
                                        label="体重(kg)">
                                        <InputNumber min={0} />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'headCirc']}
                                        label="头围(cm)">
                                        <InputNumber min={0} />
                                    </Form.Item>
                                    <Form.Item
                                        name={['model', 'bloodType']}
                                        label="血型"
                                        rules={[{ required: true, message: "请输入宝宝血型" }]}>
                                        <Select style={{ width: 120 }}>
                                            <Select.Option value="A">A型</Select.Option>
                                            <Select.Option value="B">B型</Select.Option>
                                            <Select.Option value="AB">AB型</Select.Option>
                                            <Select.Option value="O">O型</Select.Option>
                                        </Select>
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>
                            <Form.Item
                                name={['model', 'sex']}>
                                <Radio.Group >
                                    <Radio value="男">男</Radio>
                                    <Radio value="女">女</Radio>
                                </Radio.Group>
                            </Form.Item>

                            <Form.Item>
                                <Space>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        loading={this.state.loading}
                                    >确定</Button>
                                    <Button onClick={this.ResetForm}>重设</Button>
                                    <Button danger
                                        onClick={this.showConfirm}
                                        disabled={!datas.id}>删除</Button>
                                </Space>
                            </Form.Item>
                        </TabPane>
                        <TabPane tab="宝宝大事记" key="2"></TabPane>
                        <TabPane tab="成长曲线" key="3">
                            <G2Line ParentData={this.state.GrowthData} onRef={this.onRef} />
                        </TabPane>
                    </Tabs>
                </Form>
            </div>
        )
    }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
    Category
}))(ChildEdit);